<!--
 * @Author       : wfl
 * @LastEditors: root zhangpengpeng@ikingtech.com
 * @description  :
 * @updateInfo   :
 * @Date         : 2023-11-28 10:35:00
 * @LastEditTime: 2024-03-20 11:15:38
-->
<template>
  <div class="my-media">
    <n-upload
      accept="image/*"
      :action="uploadUrl"
      :multiple="true"
      :show-file-list="false"
      :data="form"
      @before-upload="beforeUpload"
      @finish="finishUpload"
    >
      <n-upload-dragger>
        <n-spin :show="loading">
          <div
            class="g-upload-image-wrap"
          >
            <div class="g-upload-image-content">
              <div class="g-upload-tip">
                <n-icon size="60">
                  <IconImg />
                </n-icon>
                <div>点击或拖拽文件到这里上传</div>
              </div>
            </div>
          </div>
        </n-spin>
      </n-upload-dragger>
    </n-upload>
    <n-spin :show="spinShow" :delay="1000">
      <n-tabs
        animated
        placement="left"
        :value="tabsValue"
        @update:value="TabsChange"
      >
        <n-tab-pane name="IMAGE" tab="图片">
          <div v-for="i in dataList" :key="i" class="img-list">
            <n-image
              lazy
              :intersection-observer-options="{
                root: '#image-scroll-container'
              }"
              :src="`${i.path}`"
            />
            <div class="operate">
              <IconDelete @click="handDelete(i)" />
            </div>
          </div>
        </n-tab-pane>
        <n-tab-pane name="VIDEO" tab="视频">
          <div v-for="i in dataList" :key="i" class="img-list">
            <!-- autoplay -->
            <video
              :ref="(el) => registerVideoRef(el, i.id)"
              :key="`video-${i.id}`"
              loop
              :style="{ maxWidth: '100%' }"
            >
              <source :src="`${i.path}`" type="video/mp4">
            </video>
            <div class="video-operate">
<!--              <IconPlayBack @click="handPlayBack(i.id)" />-->
              <IconDelete @click="handDelete(i)" />
            </div>
          </div>
        </n-tab-pane>
        <n-tab-pane name="OTHER" tab="其它">
          <div v-for="i in dataList" :key="i" class="img-list">
            <img
              v-lazy="`${i.path}`"
              :style="{ maxWidth: '100%' }"
            >
            <div class="operate">
              <IconDelete @click="handDelete(i)" />
            </div>
          </div>
        </n-tab-pane>
      </n-tabs>
      <div v-if="dataList?.length===0" class="no-data">
        <n-icon size="40">
          <IconNoData />
        </n-icon>
        <p>暂无数据</p>
      </div>
      <div class="page-list">
        <n-pagination
          v-model:page="pageValue.page"
          :item-count="pageValue.total"
          :page-size="pageValue.size"
          size="medium"
          show-quick-jumper
          show-size-picker
          :page-sizes="[20, 30, 40, 50, 60]"
          @update:page="pageChange"
          @update:page-size="sizeChange"
        />
      </div>
    </n-spin>
  </div>
</template>

<script lang="ts">
import { defineComponent, onMounted } from 'vue'
import { UploadFileInfo, useDialog, useMessage, NUpload, NUploadDragger, NSpin, NPagination, NImage } from 'naive-ui'
import { IconDelete, IconImg, IconNoData, IconPlayBack } from '@/icons'
import { getImages, deleteProjectFile } from '@/api/image'
import { useEditorStore } from '@/store/editor'
import { storeToRefs } from 'pinia'
import { ikStore, _ } from 'iking-utils'
import basicImg from '@/assets/img/logo.png'
export default defineComponent({
  name: 'MyMedia',
  components: {
    IconDelete,
    NUpload,
    NUploadDragger,
    NSpin,
    IconImg,
    NPagination,
    IconNoData,
    IconPlayBack,
    NImage,
  },
  setup() {
    const videoRefs = ref<{[key: string]: HTMLVideoElement | undefined;}>({})
    const loading = ref(false)
    const tabsValue = ref<string>('IMAGE')
    const dataList = ref<any>()
    const projectId = computed(() => ikStore.session.getItem('project_id') ?? screen.value.groupId)
    const pageValue = ref<any>({
      page:1,
      total:0,
      size: 20,
    })
    const spinShow = ref<boolean>(false)
    const nMessage = useMessage()
    const {uploadUrl } = useEnvUrl()
    const form = ref({
      key: '',
      token: '',
      projectId: '',
      dir: '',
    })
    const editorStore = useEditorStore()
    const { screen } = storeToRefs(editorStore)
    const projectImages = ref([])
    const typeObj = reactive({
      images: [],
      videos: [],
      others: [],
    })
    // 获取项目图片
    const getProjectList = async () => {
      spinShow.value = true
      dataList.value  = []
      const { data,success,msg,total }: any = await getImages({
        type:'COMMON',
        // 文件类型
        fileType:tabsValue.value,
        page: pageValue.value.page,
        rows: pageValue.value.size,
      })
      if (success) {
        dataList.value = data
        pageValue.value.total = total
        spinShow.value = false
      }else {
        spinShow.value = false
      }
    }


    // 上传前的回调
    const beforeUpload = async (options: { file: UploadFileInfo; }) => {
      try {
        loading.value = true
        form.value.token = localStorage.getItem(
          import.meta.env.VITE_DATAV_TOKEN_KEY as string,
        )
        form.value.dir = (projectId.value) as any
        return true
      } catch (error) {
        loading.value = false
        nMessage.error(error.message)
      }
      return false
    }
    // 上传后的回调
    const finishUpload = (options: {
      file: UploadFileInfo
      event?: ProgressEvent
    }) => {
      loading.value = false
      const { code,msg } = JSON.parse((options.event.target as XMLHttpRequest).response)
      if (code !== 0)
        nMessage.error(msg)
      else
        getProjectList()
    }

    const nDialog = useDialog()
    // 点击删除
    const handDelete = i => {
      const d = nDialog.create({
        content: `请确认该资源在项目中未使用，否则可能导致页面显示异常！`,
        negativeText: '取消',
        positiveText: '确定',
        showIcon: false,
        closable: false,
        onPositiveClick: async () => {
          d.loading = true
          try {
            const res = await deleteProjectFile([i.id])
            if (res.success) getProjectList()
            else
              nMessage.warning(res.msg)
          } catch (error) {
            nMessage.error(error.message)
          }
        },
      })
    }
    // 切换页发生变化
    const TabsChange = (value: string)=>{
      tabsValue.value = value
      getProjectList()
    }
    // 分页发生变化
    const pageChange = (value:number)=>{
      pageValue.value.page = value
      getProjectList()
    }
    // 分页数发生变化
    const sizeChange = (value:number)=>{
      pageValue.value.size = value
      getProjectList()
    }
    // 初始掉调用
    onMounted(() => {
      getProjectList()
    })
    // 视屏定义ref
    const registerVideoRef = (el: HTMLVideoElement | undefined, id: string)=>{
      if (el) {
        videoRefs.value[id] = el
      }
    }
    // 点击播放
    const handPlayBack = async (itemId:any)=>{
      const videoElement = videoRefs.value[itemId]
      if (videoElement && !videoElement.paused) {
        videoElement.pause()
      } else if (videoElement) {
        try {
          await videoElement.play()
        } catch (error) {
          console.error('播放视频时出错:', error)
        }
      }
    }
    return {
      tabsValue,
      projectImages,
      uploadUrl,
      form,
      loading,
      typeObj,
      handDelete,
      beforeUpload,
      finishUpload,
      dataList,
      pageValue,
      TabsChange,
      pageChange,
      sizeChange,
      spinShow,
      handPlayBack,
      videoRefs,
      registerVideoRef,
      basicImg,
    }
  },
})
</script>

<style lang="scss" soped>
.n-tabs {
  .n-tab-pane {
    background: transparent;
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(150px, 290px));
    grid-gap: 18px;
    justify-content: center;
    overflow: auto;
    height: calc(100vh - 284px);
    padding-top: 9px !important;
  }
}

.my-media {
  display: flex;
  flex-direction: column;
  grid-template-columns: repeat(auto-fill, minmax(150px, 295px));
  grid-gap: 18px;
  justify-content: center;
  margin-top: 12px;

  .n-upload {
    .n-upload-trigger {
      height: 100%;

      .n-upload-dragger {
        height: 100%;
        color: #adaaaa;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
  }

  .img-list {
    display: flex;
    justify-content: center;
    align-items: center;
    border: 1px solid #36363661;
    box-shadow: 0 0 5px 4px rgb(0 0 0 / 21%);
    border-radius: 8px;
    transition: all 0.25s;
    max-height: 300px;
    background: #00000061;
    position: relative;
    padding: 4px;

    img {
      max-width: 100%;
      max-height: 100%;
    }
    &:hover {
      box-shadow: 0 0 200px 200px #000000be inset;
      .video-operate,.operate{
        display: block;
      }
      img {
        opacity: 0.5;
      }
    }
    .icon {
      cursor: pointer;
      background-color: rgb(50 50 50 / 59%);
      width: 38px;
      height: 37px;
      padding: 0 8px;
      border-radius: 4px;
      fill: #fff;
    }
    img {
      z-index: 1;
      transition: all 0.35s ease-in-out;
    }
  }
}
.video-operate,.operate{
  position: absolute;
  transition: all 0.35s ease-in-out;
  z-index: 2;
  display: none;
}
.video-operate{
  .icon{
    &:nth-child(1){
        margin-right: 16px;
        &:hover{
          fill: #2483ff;
          background-color: rgb(50 50 50 / 30.1%);
        }
      }
      &:nth-child(2){
        &:hover{
          fill: var(--el-color-danger-light-3);
          background-color: rgb(50 50 50 / 30.1%);
        }
      }
  }
}
.operate{
  .icon{
    &:nth-child(1){
        margin-right: 16px;
        &:hover{
          fill: var(--el-color-danger-light-3);
          background-color: rgb(50 50 50 / 30.1%);
        }
      }
  }
}
.page-list{
  display: flex;
  justify-content: flex-end;
  padding-right: 24px;
}
.no-data{
  position: fixed;
  left:60px;
  top: 35%;
  z-index: 10;
  width: 100%;
  text-align: center;
  p{
    font-size: 14px;
    color: #adaaaa;
  }
  svg{
    color: #adaaaa !important;
  }
}
</style>
